import { check } from '@tauri-apps/plugin-updater';
import { ask, message } from '@tauri-apps/plugin-dialog';
import { relaunch } from '@tauri-apps/plugin-process';

export class UpdateService {
  private static instance: UpdateService;

  static getInstance(): UpdateService {
    if (!UpdateService.instance) {
      UpdateService.instance = new UpdateService();
    }
    return UpdateService.instance;
  }

  async checkForUpdates(showNoUpdates = false): Promise<void> {
    try {
      console.log('检查更新...');
      const update = await check();

      if (update) {
        console.log('发现新版本:', update.version);
        console.log('更新内容:', update.body);

        const yes = await ask(
          `发现新版本 ${update.version}\n\n更新内容:\n${update.body || '修复了一些问题并改进了性能'}\n\n是否现在更新？`,
          {
            title: '软件更新',
            kind: 'info',
            okLabel: '立即更新',
            cancelLabel: '稍后提醒'
          }
        );

        if (yes) {
          await this.installUpdate(update);
        }
      } else if (showNoUpdates) {
        await message('当前已是最新版本', { title: '软件更新' });
      }
    } catch (error) {
      console.error('检查更新失败:', error);
      if (showNoUpdates) {
        await message('检查更新失败，请稍后重试', { title: '更新错误' });
      }
    }
  }

  private async installUpdate(update: any): Promise<void> {
    try {
      console.log('开始下载更新...');
      
      // 显示下载进度
      let downloaded = 0;
      let contentLength = 0;

      await update.downloadAndInstall((event: any) => {  // 添加event参数类型声明
        switch (event.event) {
          case 'Started':
            contentLength = event.data.contentLength || 0;
            console.log(`开始下载，文件大小: ${(contentLength / 1024 / 1024).toFixed(2)} MB`);
            break;
          case 'Progress':
            downloaded += event.data.chunkLength || 0;
            const progress = contentLength > 0 ? (downloaded / contentLength) * 100 : 0;
            console.log(`下载进度: ${progress.toFixed(1)}%`);
            break;
          case 'Finished':
            console.log('下载完成');
            break;
        }
      });

      console.log('更新安装完成，准备重启...');
      
      const restart = await ask(
        '更新已安装完成，是否现在重启应用？',
        {
          title: '重启应用',
          kind: 'info',
          okLabel: '立即重启',
          cancelLabel: '稍后重启'
        }
      );

      if (restart) {
        await relaunch();
      }
    } catch (error) {
      console.error('安装更新失败:', error);
      await message('安装更新失败，请稍后重试', { title: '更新错误' });
    }
  }

  async checkForUpdatesSilently(): Promise<void> {
    await this.checkForUpdates(false);
  }
}

export const updateService = UpdateService.getInstance();